<?php

namespace App\Repositories;

use App\Models\Menu;
use App\Models\Manager;
use App\Models\RoleAccess;
use App\Exceptions\InvalidException;
use DB;
class RoleAccessRepo
{
	//给角色分配权限
	public function givePromiss($role_id,$assess_ids)
	{

		DB::beginTransaction();
		try{
			//删除该用户的权限
			RoleAccess::where('role_id',$role_id)->delete();
			//重新添加
			$data = [];
			foreach($assess_ids as $access_id) {
				$data[] = [
					'role_id'=>$role_id,
					'access_id'=> $access_id
				];
			}
			RoleAccess::insert($data);
			DB::commit();
		} catch(\Exception $e){
			DB::rollback();
			throw new InvalidException($e->getMessage());
		}
		return true;
	}

	public function hasPromission($id,$promission,$type='any')
	{
		//判断用户是否存在
		$manager = Manager::where('id',$id)->first();

		if(!$manager || ($manager->role == 0)) {
			return false;
		}
		
			//判断权限是否存在
		$access = Access::where('promission',$promission)->first();
		if(!$access){
			return false;
		}
		if($access->type != 'any' && $access->type != strtolower($type)) {
			return false;
		}
		$roleAccess = RoleAccess::where('role_id',$role_id)->where('access_id',$access->id)->first();
		if(!$roleAccess) {
			return false;
		}
		return true;
	}
}